<?php
namespace Cyfy\Modules\Users;

/**
 * Information about a user, not the logged one.
 * 
 * @author Dandelion
 * @version 0.1
 */
class User
{
    /**
     * UserID.
     * @var int
     */
    public $uid = 0;
     
    /**
     * Full name of the user.
     * @var string
     */
    public $name = '';
    
    /**
     * Username.
     * @var string
     */
    public $username = '';
    
    /**
     * Password hash.
     * @var string
     */
    public $passwordHash = '';
    
    /**
     * Email address.
     * @var string
     */
    public $email = '';
    
    /**
     * Last login.
     * @var DateTime
     */
    public $lastLogin;
    
    /**
     * Info in array.
     */
    public $info = array();
    
    /**
     * Groups, the user is in.
     */
    public $groups = array();
    
    
    static function load($uid)
    {
        $result = \dibi :: query("SELECT [uid], [username], [name], [password] as passwordHash, [email], [lastLogin] FROM [:cyfy:Users-users] WHERE uid = %i LIMIT 1", $uid);
        // user not found
        if(!count($result)){
            return false;
        }
        
        // OK
        $u = $result -> fetch();
        
        // Load groups
        $u["groups"] = array();
        $result = \dibi :: query("SELECT [gid] FROM [:cyfy:Users-users-groups] WHERE uid = %i", $uid);
        foreach($result as $g)
        {
            $u["groups"][] = $g['gid'];
        }
        
        $user = new User();
        
        // Sets data
        $user -> uid = $u['uid'];
        $user -> username = $u['username'];
        $user -> name = $u['name'];
        $user -> passwordHash = $u['password'];
        $user -> email = $u['email'];
        $user -> lastLogin = $u['lastLogin'];
        $user -> groups = $u['groups'];
        
        // all info in one array
        $user -> info = $u;
        
        return $user;
    }
    
    /**
     * Creates a new instance of UserInfo class.
     * @param UserID
     */
    function __construct()
    {
       
    }
    
    
    

    /**
     * Information page about the user.
     *
     * If module Profile is enabled, shows values via it.
     *
     * @returns string HTML content
     */
    public function infoPage()
    {
        
        
        $output .= "<h2>{$this -> name}</h2>\n";

        // profile module
        if (\Cyfy\Modules :: isEnabled("Profile"))
        {
            $output .= \Cyfy\Modules\Profile\Module :: show($this -> uid, $this -> data);            
        }
        else
        {
            // if not, show default
            
            // last login
            if($this -> lastLogin != "0000-00-00 00:00:00")
            {
                $time = \Cyfy\Modules\Locale\Locale :: getTime($this -> lastLogin);
            }
            else
            {
                // user hasn't been signed in
                $time = Module :: t(420);
            }
        
            $output .= "<ul>\n";
            $output .= "  <li>" . Module :: t(30) . ": <strong>{$this->username}</strong></li>\n";
            $output .= "  <li>" . Module :: t(50) . ": <strong>{$this->email}</strong></li>\n";
            $output .= "  <li>" . Module :: t(70) . ": <strong>{$time}</strong></li>\n";
            $output .= "</ul>\n";
        }
        
        // GROUPS
        if (\Cyfy\Cyfy ::  permission("Users", "groups and permissions") || count($this -> groups))
        {
            $output .= "<h2>" . Module :: t(410)  . "</h2>\n";
            $output .= "<div id=\"userGroups\">\n";
            $output .= $this -> adminGetGroups();
            $output .= "</div>\n";
        }
        
        // add to group
        if (\Cyfy\Cyfy ::  permission("Users", "groups and permissions"))
        {
            $form = new Forms\AddUserToGroup();
            $form->setTemp("uid", $this -> uid);
            $output .= "<h3>" . Module :: t(430)  . "</h3>";
            $output .= $form->show();
        }
        
        // delete
        if(\Cyfy\Cyfy :: permission("Users", "edit users") || $this -> uid == Current :: $uid)
        {
            $output .= "<h2>" . Module :: t(1200) . "</h2>\n";
            $output .= "<div class=\"form-buttons\"><input value=\"" . Module :: t(1200) . "\" type=\"submit\" onclick=\"if(confirm('" . Module :: t(1201, array($this ->name)) . "')) {Cyfy.ajax('Users', 'deleteUser', '', 'uid={$this -> uid}', 'Cyfy.redirectTo(\'index\',2000)'); } return false;\" /></div>\n";
        }
        return $output;
    } 
    
    
   
    /**
     * Method which dislays groups of this user.
     * @return string HTML content - list with groups.
     */    
    public function adminGetGroups()
    {
        // if has permission, show delete button
        if (Current :: haspermission("Users", "groups and permissions")) {
            $d = true;
        } else {
            $d = false;
        }
        
        // get groups
        $groupNames = Groups :: getAll(true);
        
        $output = "<ul>";
        foreach ($this -> groups as $gid) {
            if (!$gid)
                continue;
            // possible to remove user from a group, prevents administrators from removing them from group administrators
            if ($d && !($gid == 1 && $this -> uid == Current :: $uid)) {
                $del = " <input type=\"submit\" value=\"X\" class=\"button-warning\" onclick=\"Cyfy.ajax('Users', 'removeUserFromGroup', '#userGroups', 'uid={$this -> uid}&gid={$gid}'); return false;\" />";
            } else {
                $del = "";
            }
            $output .= "<li>{$groupNames[$gid]}{$del}</li>";
        }
        $output .= "</ul>";
        return $output;
    }
    
    
    
    /**
     * Method which removes USER from a GROUP.
     * @return bool true, if successfull.
     */
    public function removeFromGroup($gid)
    {
        // if no permission
        if (!Current :: haspermission("Users", "groups and permissions"))
        {
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }

        // if administrator and self
        if ($gid == 1 && $this -> uid == Current :: $uid)
        {
            \Cyfy\Message :: set(self :: t(440), \Cyfy\Message::ERROR);
            return false;
        }

        // do the query
        $where = array(
            'uid' => $this -> uid,
            'gid' => $gid
        );
        \dibi :: query("DELETE FROM [:cyfy:Users-users-groups] WHERE %and", $where);

        // removes from current array
        $this -> groups = remove_item_by_value($this -> groups, $gid);        
        
        return true;
    }

}

